package cn.wzg.netbase.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpsUtil {
    public static void sendHttpRequest(Context context,final String address, final HttpCallbackListener listener){
        Looper looper=context.getMainLooper();
        Handler handler=new Handler(looper){
            @Override
            public void handleMessage(@NonNull Message msg) {
                String str= (String) msg.obj;
                //将返回的数据抛给回调接口
                if(listener!=null){
                    //回调onFinish()方法
                    listener.onFinish(str);
                }
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpsURLConnection connection = null;
                try{
                    //1.获得HttpURLConnection类的实例
                    URL url = new URL(address);
                    connection = (HttpsURLConnection)url.openConnection();

                    //2.设置HTTP请求的参数
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    //3.调用connect()方法连接远程资源，并对服务器响应进行判断
                    connection.connect();
                    int responseCode = connection.getResponseCode();
                    if(responseCode == HttpsURLConnection.HTTP_OK){
                        //进行数据读取操作
                        InputStream in = connection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine())!=null){
                            sb.append(line);
                        }
                        Message message=new Message();
                        message.obj=sb.toString();
                        message.what=0;
                        handler.sendMessage(message);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(connection!=null)
                    {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}
